import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:sports_new/entity/expert/match_play_entity.dart';
import 'package:sports_new/entity/expert/plan_Info_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/utils/mode_config.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/view/king/items/history_label.dart';
import 'package:sports_new/widgets/base/qkd_image.dart';
import '../../../entity/match/expert_views_entity.dart';
import '../../../resources/styles.dart';
import '../../../widgets/base/qkd_text.dart';

const _notReady = Color(0xFFB58D76);

extension PlanPlayContentItemEx1 on PlanPlayContentItem {
  bool get selected => (s == 1 || s == 2);
}

class MatchPlayView extends StatelessWidget {
  MatchPlayView(
      {super.key,
      this.matchPlay,
      this.match,
      this.readable = true,
      this.roomId});

  final MatchPlayEntity? matchPlay;
  final bool readable;
  final int? roomId;
  final MatchBries? match;

  bool getResult = false;
  List<PlanItemShowEntity> get shows =>
      matchPlay?.itemShow?.filter((item) => item.matchId == match?.matchId) ??
      [];

  String? get matchScore {
    if (match?.sportsId == 2) {
      if (match?.homeScore == null || match?.guestScore == null) {
        return "vs";
      }
      return "${match?.guestScore} : ${match?.homeScore}";
    }
    if (match?.homeScore90 == null || match?.guestScore90 == null) {
      return "vs";
    }
    if (!(match?.isMatchStart ?? false)) {
      return "vs";
    }
    return "${match?.homeScore90} : ${match?.guestScore90}";
  }

  bool get isViewpoint => matchPlay?.type == MatchPlayType.viewpoint;

  @override
  Widget build(BuildContext context) {
    // TYPE_0(0, "未开"),
    // TYPE_1(1, "中"),
    // TYPE_2(2, "未中"),
    // TYPE_3(3, "取消"),
    // TYPE_4(4, "走"),

    getResult = true;

    final status = () {
      if (shows.isNotEmpty) {
        return shows.first.status ?? 0;
      }
      return matchPlay?.status ?? 0;
    }.call();

    final leftRanking =
        match?.sportsId == 2 ? match?.guestRanking : match?.homeRanking;
    final leftName = match?.sportsId == 2 ? match?.guestName : match?.homeName;
    final rightRanking =
        match?.sportsId == 2 ? match?.homeRanking : match?.guestRanking;
    final rightName = match?.sportsId == 2 ? match?.homeName : match?.guestName;
    final leftTeam = Text.rich(
      TextSpan(children: [
        if ((leftRanking?.isNotEmpty ?? false) && isViewpoint)
          TextSpan(
              text: "[$leftRanking] ",
              style: const TextStyle(fontSize: 12, color: Colours.grey99)),
        TextSpan(
            text: leftName ?? "",
            style: const TextStyle(
                fontSize: 16, color: Colours.text, fontWeight: FontWeight.w500))
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      textAlign: TextAlign.right,
    );
    final rightTeam = Text.rich(
      TextSpan(children: [
        TextSpan(
            text: rightName ?? "",
            style: const TextStyle(
                fontSize: 16,
                color: Colours.text,
                fontWeight: FontWeight.w500)),
        if ((rightRanking?.isNotEmpty ?? false) && isViewpoint)
          TextSpan(
              text: " [$rightRanking]",
              style: const TextStyle(fontSize: 12, color: Colours.grey99))
      ]),
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      textAlign: TextAlign.left,
    );
    final itemPlayInfo =
        matchPlay?.itemShow?.filter((item) => item.matchId == match?.matchId) ??
            [];
    final container = Container(
      padding: EdgeInsets.fromLTRB(isViewpoint ? 0 : 16, isViewpoint ? 12 : 0,
          isViewpoint ? 0 : 16, isViewpoint ? 12 : 12),
      decoration: BoxDecoration(
        color: Colours.white,
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        children: [
          if (isViewpoint) ...[
            DefaultTextStyle(
                style: const TextStyle(color: Colours.grey66, fontSize: 12),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    QkdText(match?.sportsId == 2 ? "[篮]\u2000" : "[足]\u2000"),
                    QkdText(
                        "${match?.leagueName} ${match?.rounds ?? ""} ${match?.matchTimeDate?.formatedString("MM/dd HH:mm") ?? ""} "),
                    if (itemPlayInfo.isNotEmpty)
                      QkdText(itemPlayInfo.first.appPlayTypeName ?? "",
                          color: Colours.blue2766D6),
                    if ((match?.weatherCn?.trim().length ?? 0) > 0)
                      const Spacer(),
                    if ((match?.weatherCn?.trim().length ?? 0) > 0)
                      QkdText(match?.weatherCn ?? ""),
                  ],
                )),
            const SizedBox(height: 12)
          ],
          isViewpoint
              ? Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    Flexible(
                      flex: 1,
                      fit: FlexFit.tight,
                      child: Center(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Column(
                              children: [
                                SizedBox(width: 18, height: 18),
                                if ((rightRanking?.isNotEmpty ?? false))
                                  QkdText('[$leftRanking]',
                                      fontSize: 12, color: Colours.grey99)
                              ],
                            ),
                            Column(
                              children: [
                                CachedNetworkImage(
                                    height: 18,
                                    width: 18,
                                    imageUrl: (match?.sportsId == 1
                                            ? match?.homeLogo
                                            : match?.guestLogo) ??
                                        "",
                                    placeholder: (context, url) =>
                                        Styles.placeholderIcon(),
                                    errorWidget: (context, url, error) =>
                                        Image.asset(
                                          Utils.getImgPath(
                                              '${match?.sportsId == 1 ? "zq" : "lq"}_placeholder.png'),
                                          height: 18,
                                          width: 18,
                                        )).paddingOnly(left: 2),
                                QkdText(leftName ?? '',
                                    fontSize: 16,
                                    fontWeight: FontWeight.w500,
                                    color: Colours.text,
                                    maxLines: 1)
                              ],
                            ),
                          ],
                        ),
                      ),
                    ),
                    Container(
                      constraints: BoxConstraints(
                        minWidth: 60, // 最小宽度
                      ),
                      margin: const EdgeInsets.symmetric(horizontal: 4),
                      alignment: Alignment.center,
                      // width: 60,
                      child: QkdText(
                        matchScore ?? "vs",
                        maxLines: 1,
                        color: Colours.text292D32,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                    Flexible(
                      flex: 1,
                      fit: FlexFit.tight,
                      child: Center(
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Flexible(
                              child: Column(
                                children: [
                                  CachedNetworkImage(
                                      height: 18,
                                      width: 18,
                                      imageUrl: (match?.sportsId == 1
                                              ? match?.guestLogo
                                              : match?.homeLogo) ??
                                          "",
                                      placeholder: (context, url) =>
                                          Styles.placeholderIcon(),
                                      errorWidget: (context, url, error) =>
                                          Image.asset(
                                            Utils.getImgPath(
                                                '${match?.sportsId == 1 ? "zq" : "lq"}_placeholder.png'),
                                            height: 18,
                                            width: 18,
                                          )).paddingOnly(left: 2),
                                  QkdText(
                                    rightName ?? '',
                                    fontSize: 16,
                                    fontWeight: FontWeight.w500,
                                    color: Colours.text,
                                    maxLines: 1,
                                  )
                                ],
                              ),
                            ),
                            Column(
                              children: [
                                SizedBox(width: 18, height: 18),
                                if ((rightRanking?.isNotEmpty ?? false))
                                  QkdText('[$rightRanking]',
                                      fontSize: 12, color: Colours.grey99)
                              ],
                            )
                          ],
                        ),
                      ),
                    ),
                  ],
                ).tap(() {
                  Utils.onEvent("plan_detail_match_view", params: {
                    "match_id": match?.matchId,
                    'param2': roomId == null ? '0' : '1'
                  });
                  if (match?.sportsId == 1) {
                    Get.toNamed(Routes.zqMatchDetail,
                        arguments: match?.matchId);
                  }
                  if (match?.sportsId == 2) {
                    Get.toNamed(Routes.lqMatchDetail,
                        arguments: match?.matchId);
                  }
                })
              : Row(
                  children: [
                    if (matchPlay?.type == MatchPlayType.planForm &&
                        match?.jcMatchNo.hasValue == true)
                      QkdText(
                        match?.jcMatchNo ?? "",
                        fontSize: 12,
                        color: Colours.grey99,
                      ).paddingOnly(right: 4),
                    leftTeam,
                    Container(
                      margin: const EdgeInsets.symmetric(horizontal: 6),
                      alignment: Alignment.center,
                      // width: 60,
                      child: QkdText(matchScore ?? "vs",
                          maxLines: 1,
                          color: Colours.text292D32,
                          fontWeight: FontWeight.w500),
                    ),
                    Container(width: 2),
                    rightTeam,
                    if (matchPlay?.type == MatchPlayType.planForm &&
                        match?.jcMatchNo.hasValue == true)
                      QkdText(
                        match?.jcMatchNo ?? "",
                        fontSize: 12,
                        color: Colours.transparent,
                      ).paddingOnly(left: 4),
                  ],
                ).tap(() {
                  Utils.onEvent("plan_detail_match_view", params: {
                    "match_id": match?.matchId,
                    'param2': roomId == null ? '0' : '1'
                  });
                  if (match?.sportsId == 1) {
                    Get.toNamed(Routes.zqMatchDetail,
                        arguments: match?.matchId);
                  }
                  if (match?.sportsId == 2) {
                    Get.toNamed(Routes.lqMatchDetail,
                        arguments: match?.matchId);
                  }
                }),
          const SizedBox(height: 10),
          ((matchPlay?.canRead ?? false)
                  ? _playContent()
                  : Stack(
                      alignment: AlignmentDirectional.center,
                      children: [
                        Image.asset(
                          Utils.getImgPath('plan_lock_bg.png'),
                          height: 40,
                        ),
                        Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Image.asset(
                                width: 16, Utils.getImgPath('plan_lock.png')),
                            SizedBox(width: 4),
                            QkdText(
                              '支付后可查看方案',
                              fontSize: 12,
                              color: Colours.grey66,
                            )
                          ],
                        )
                      ],
                    ))
              .paddingSymmetric(horizontal: isViewpoint ? 12 : 0),
          if (isViewpoint) const SizedBox(height: 10),
        ],
      ),
    );
    return Stack(children: [
      container,
      if (isViewpoint)
        Positioned(
          top: 32,
          right: 0,
          child: HistoryLabel.viewpoint(state: status, width: 36),
        )
    ]);
  }

// 1001,"足球全场胜平负"
// 1002,"足球全场让球胜平负"
// 1003,"足球全场比分"
// 1004,"足球全场总进球数"
// 1005,"足球半全场"
// 1006,"足球让球/亚盘"
// 1007,"足球全场进球数大小球"
// 1008,"足球双平玩法"
  Widget _playContent() {
    final shows =
        matchPlay?.itemShow?.filter((item) => item.matchId == match?.matchId) ??
            [];
    final List<Widget> children = [];

    Widget showWidget(PlanItemShowEntity show) {
      switch (show.playType) {
        case 1001:
          return _playContentSpf(show);
        case 1002:
          return _playContentRqspf(show);
        case 1004:
          return _playContentJqs(show);
        case 1005:
          return _playContentBqc(show);
        case 1006:
          return _playContentRq(show);
        case 1007:
          return _playContentDx(show);
        case 1008:
          return _playContentSp(show);
        case 1009:
          return _playContentRq(show);
        case 2001:
          return _lqSf(show);
        case 2002:
          return _lqRqsf(show);
        case 2003:
          return _lqDx(show);
        default:
          return Container();
      }
    }

    for (var s in shows) {
      if (children.isNotEmpty) {
        children.add(const SizedBox(height: 10));
      }
      children.add(showWidget(s));
    }
    return Column(children: children);
  }

  Widget _playContentSp(PlanItemShowEntity show) {
    final children = <Widget>[];
    var plays = show.sp ?? [];
    if (matchPlay?.canRead == false && plays.isNotEmpty) {
      plays = [plays.first];
    }
    int snum = 0;
    for (PlanPlayContent sp in plays) {
      for (PlanPlayContentItem l in sp.list ?? []) {
        if ((l.s ?? 0) > 0) {
          snum += 1;
        }
      }
    }
    for (PlanPlayContent sp in plays) {
      Map<String, PlanPlayContentItem> map = {};
      bool haveResult = false;
      for (PlanPlayContentItem l in sp.list ?? []) {
        // log("篮球让球胜负 ${l.toJson()}");
        map[l.i ?? ""] = l;
        // if ((l.s ?? 0) > 0) {
        //   snum += 1;
        // }
        if (l.r == 1) {
          haveResult = true;
        }
      }
      if (children.isNotEmpty) {
        children.add(const SizedBox(height: 6));
      }
      children.add(Row(
        children: [
          _matchInfoWhiteBox(
              QkdText(readable ? (sp.line.noValue ? "0" : sp.line!) : "让"),
              show: readable),
          const SizedBox(
            width: 8.5,
          ),
          Expanded(
            child: _matchInfoWhiteBox(
                Row(
                  children: [
                    _checkContent1(map['s'], snum, haveResult),
                    const VerticalDivider(width: 0.5, color: Colours.greyEA),
                    _checkContent1(map['p'], snum, haveResult),
                    const VerticalDivider(width: 0.5, color: Colours.greyEA),
                    _checkContent1(map['f'], snum, haveResult)
                  ],
                ),
                width: double.infinity),
          ),
        ],
      ));
    }
    // }
    return Column(children: children);
  }

  Widget _playContentSpf(PlanItemShowEntity show) {
    final spf = show.spf;
    List<Widget> children = [];
    int snum = 0;
    bool haveResult = false;
    Map<String, PlanPlayContentItem> eles = {};
    for (PlanPlayContentItem element in spf?.list ?? []) {
      if (element.r == 1) {
        haveResult = true;
      }
      if (element.selected) {
        snum += 1;
      }
      eles[element.i ?? ""] = element;
    }
    for (var i in ["s", "p", "f"]) {
      PlanPlayContentItem? element = eles[i];
      children.add(_checkContent1(element, snum, haveResult));
      if (i != "f") {
        children.add(const VerticalDivider(width: 1));
      }
    }
    return Row(
      children: [
        if (isViewpoint) ...[
          _matchInfoWhiteBox(QkdText(readable ? "0" : "让"), show: readable),
          const SizedBox(width: 8.5),
        ],
        Expanded(
            child: _matchInfoWhiteBox(Row(children: children), width: null)),
      ],
    );
  }

  Widget _playContentRqspf(PlanItemShowEntity show) {
    final lineLen = show.rqSpf?.length ?? 0;
    int snum = 0;
    bool haveResult = false;
    for (var i = 0; i < lineLen; i++) {
      final srqspf = show.rqSpf?[i];
      for (PlanPlayContentItem element in srqspf?.list ?? []) {
        if (element.r == 1) {
          haveResult = true;
        }
        if (element.selected) {
          snum += 1;
        }
      }
    }

    List<Widget> colChildren = [];
    for (var i = 0; i < lineLen; i++) {
      final srqspf = show.rqSpf![i];
      List<Widget> rowChildren = [];
      Map<String, PlanPlayContentItem> eles = {};
      for (PlanPlayContentItem element in srqspf.list ?? []) {
        eles[element.i ?? ""] = element;
      }
      for (var j in ["s", "p", "f"]) {
        PlanPlayContentItem? element = eles[j];
        rowChildren.add(_checkContent1(element, snum, haveResult));
        if (j != "f") {
          rowChildren.add(const VerticalDivider(width: 1));
        }
      }
      colChildren.add(Row(
        children: [
          _matchInfoWhiteBox(QkdText(readable ? (srqspf.line ?? "") : "让"),
              show: readable),
          const SizedBox(width: 8.5),
          Expanded(
              child: _matchInfoWhiteBox(
                  Row(
                    children: rowChildren,
                  ),
                  width: null))
        ],
      ));
      if (i < lineLen - 1) {
        colChildren.add(const SizedBox(height: 6));
      }
    }

    return Column(children: colChildren);
  }

  Widget _playContentJqs(PlanItemShowEntity show) {
    final jqs = show.jqs;
    int snum = 0;
    bool haveResult = false;
    PlanPlayContentItem? t0;
    PlanPlayContentItem? t1;
    PlanPlayContentItem? t2;
    PlanPlayContentItem? t3;
    PlanPlayContentItem? t4;
    PlanPlayContentItem? t5;
    PlanPlayContentItem? t6;
    PlanPlayContentItem? t7;
    for (PlanPlayContentItem ele in jqs?.list ?? []) {
      if (ele.r == 1) {
        haveResult = true;
      }
      if (ele.selected) {
        snum += 1;
      }
      switch (ele.i) {
        case "t0":
          t0 = ele;
          break;
        case "t1":
          t1 = ele;
          break;
        case "t2":
          t2 = ele;
          break;
        case "t3":
          t3 = ele;
          break;
        case "t4":
          t4 = ele;
          break;
        case "t5":
          t5 = ele;
          break;
        case "t6":
          t6 = ele;
          break;
        case "t7":
          t7 = ele;
          break;
      }
    }
    return Row(
      children: [
        if (!isViewpoint) ...[
          _matchInfoWhiteBox(
              Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: "总进球".split("").map((e) => QkdText(e)).toList()),
              height: 40 * 2 + 6),
          const SizedBox(width: 8.5)
        ],
        Expanded(
          child: Column(
            children: [
              _matchInfoWhiteBox(
                  Row(
                    children: [
                      Expanded(
                          child: Row(
                        children: [
                          _checkContent1(t0, snum, haveResult),
                          const VerticalDivider(width: 1),
                          _checkContent1(t1, snum, haveResult),
                        ],
                      )),
                      const VerticalDivider(width: 1),
                      Expanded(
                          child: Row(
                        children: [
                          _checkContent1(t2, snum, haveResult),
                          const VerticalDivider(width: 1),
                          _checkContent1(t3, snum, haveResult),
                        ],
                      ))
                    ],
                  ),
                  width: null),
              const SizedBox(height: 6),
              _matchInfoWhiteBox(
                  Row(
                    children: [
                      Expanded(
                          child: Row(
                        children: [
                          _checkContent1(t4, snum, haveResult),
                          const VerticalDivider(width: 1),
                          _checkContent1(t5, snum, haveResult),
                        ],
                      )),
                      const VerticalDivider(width: 1),
                      Expanded(
                          child: Row(
                        children: [
                          _checkContent1(t6, snum, haveResult),
                          const VerticalDivider(width: 1),
                          _checkContent1(t7, snum, haveResult),
                        ],
                      )),
                    ],
                  ),
                  width: null),
            ],
          ),
        ),
      ],
    );
  }

  Widget _playContentBqc(PlanItemShowEntity show) {
    final bqc = show.bqc;
    final List data = [
      [
        "胜",
        ["ss", "sp", "sf"]
      ],
      [
        "平",
        ["ps", "pp", "pf"]
      ],
      [
        "负",
        ["fs", "fp", "ff"]
      ],
    ];
    int snum = 0;
    bool haveResult = false;
    Map<String, PlanPlayContentItem> map = {};
    for (PlanPlayContentItem element in bqc?.list ?? []) {
      if (element.r == 1) {
        haveResult = true;
      }
      if (element.selected) {
        snum += 1;
      }
      map[element.i ?? ""] = element;
    }

    List<Widget> colChildren = [];

    for (var i = 0; i < data.length; i++) {
      List tags = data[i][1];
      List items = tags.map((str) => map[str]).toList();
      colChildren.add(Row(
        children: [
          Expanded(
              child: _matchInfoWhiteBox(
                  Row(
                    children: [
                      _checkContent1(items[0], snum, haveResult),
                      const VerticalDivider(width: 1),
                      _checkContent1(items[1], snum, haveResult),
                      const VerticalDivider(width: 1),
                      _checkContent1(items[2], snum, haveResult),
                    ],
                  ),
                  width: null))
        ],
      ));
      if (i < 2) {
        colChildren.add(const SizedBox(height: 6));
      }
    }
    return Row(
      children: [
        if (!isViewpoint) ...[
          _matchInfoWhiteBox(
              Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: "半全场".split("").map((e) => QkdText(e)).toList()),
              height: 40 * data.length + 6 * (data.length - 1)),
          Container(width: 8.5)
        ],
        Expanded(child: Column(children: colChildren)),
      ],
    );
  }

  Widget _playContentDx(PlanItemShowEntity show) {
    List<Widget> children = [];
    int line = 0;
    int totalLen = show.dx?.length ?? 0;
    for (PlanPlayContent dx1 in show.dx ?? []) {
      PlanPlayContentItem? d;
      PlanPlayContentItem? x;
      int snum = 0;
      bool haveResult = false;
      for (PlanPlayContentItem element in dx1.list ?? []) {
        if (element.r == 1) {
          haveResult = true;
        }
        switch (element.i) {
          case "d":
            d = element;
            break;
          case "x":
            x = element;
            break;
        }
        if (element.s == 1 || element.s == 2) {
          snum += 1;
        }
      }
      if (d == null || x == null) {
        continue;
      }
      final box = _matchInfoWhiteBox(
          Row(
            children: [
              _checkContent1(d, snum, haveResult),
              const VerticalDivider(width: 0.5, color: Colours.greyEA),
              _checkContent("进球数", "${dx1.line}"),
              const VerticalDivider(width: 0.5, color: Colours.greyEA),
              _checkContent1(x, snum, haveResult),
            ],
          ),
          width: double.infinity);
      children.add(box);
      if (line++ < totalLen - 1) {
        children.add(const SizedBox(height: 6));
      }
    }
    return Row(
      children: [
        if (!isViewpoint) ...[
          _matchInfoWhiteBox(
              Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: "大小球".split("").map((e) => QkdText(e)).toList()),
              height: 40 * totalLen + 6 * (totalLen - 1)),
          const SizedBox(width: 8.5)
        ],
        Expanded(child: Column(children: children)),
      ],
    );
  }

  Widget _lqSf(PlanItemShowEntity show) {
    // final itemshows = planInfo?.itemShow?.filter((item) => item.matchId == match?.matchId) ?? [];
    final children = <Widget>[];
    // for (var show in itemshows) {
    for (PlanPlayContent sf in show.lqSf == null ? [] : [show.lqSf!]) {
      Map<String, PlanPlayContentItem> map = {};
      int snum = 0;
      bool haveResult = false;
      for (PlanPlayContentItem l in sf.list ?? []) {
        // log("篮球让球胜负 ${l.toJson()}");
        map[l.i ?? ""] = l;
        if ((l.s ?? 0) > 0) {
          snum += 1;
        }
        if (l.r == 1) {
          haveResult = true;
        }
      }
      if (children.isNotEmpty) {
        children.add(const SizedBox(height: 10));
      }
      children.add(_matchInfoWhiteBox(
          Row(
            children: [
              _checkContent1(map['f'], snum, haveResult),
              const VerticalDivider(width: 0.5, color: Colours.greyEA),
              _checkContent1(map['s'], snum, haveResult)
            ],
          ),
          width: double.infinity));
    }
    // }
    return Column(children: children);
  }

  Widget _lqRqsf(PlanItemShowEntity show) {
    final children = <Widget>[];

    for (PlanPlayContent rqsf in show.lqRqSf ?? []) {
      Map<String, PlanPlayContentItem> map = {};
      int snum = 0;
      bool haveResult = false;
      for (PlanPlayContentItem l in rqsf.list ?? []) {
        // log("篮球让球胜负 ${l.toJson()}");
        map[l.i ?? ""] = l;
        if ((l.s ?? 0) > 0) {
          snum += 1;
        }
        if (l.r == 1) {
          haveResult = true;
        }
      }
      final line = rqsf.line ?? "";
      final zhu = "主${line.startsWith("-") ? line : "+$line"}";
      if (children.isNotEmpty) {
        children.add(const SizedBox(height: 10));
      }
      children.add(_matchInfoWhiteBox(
          Row(
            children: [
              _checkContent1(map['f'], snum, haveResult),
              const VerticalDivider(width: 0.5, color: Colours.greyEA),
              _checkContent("让分", zhu),
              const VerticalDivider(width: 0.5, color: Colours.greyEA),
              _checkContent1(map['s'], snum, haveResult)
            ],
          ),
          width: double.infinity));
    }

    return Column(children: children);
  }

  Widget _lqDx(PlanItemShowEntity show) {
    final children = <Widget>[];

    for (PlanPlayContent dx in show.lqDx ?? []) {
      Map<String, PlanPlayContentItem> map = {};
      int snum = 0;
      bool haveResult = false;
      for (PlanPlayContentItem l in dx.list ?? []) {
        // log("篮球大小 ${l.toJson()}");
        map[l.i ?? ""] = l;
        if ((l.s ?? 0) > 0) {
          snum += 1;
        }
        if (l.r == 1) {
          haveResult = true;
        }
      }
      children.add(_matchInfoWhiteBox(
          Row(
            children: [
              _checkContent1(map['d'], snum, haveResult),
              const VerticalDivider(width: 0.5, color: Colours.greyEA),
              _checkContent("总分", dx.line ?? ''),
              const VerticalDivider(width: 0.5, color: Colours.greyEA),
              _checkContent1(map['x'], snum, haveResult)
            ],
          ),
          width: double.infinity));
    }

    return Column(children: children);
  }

  Widget _playContentRq(PlanItemShowEntity show) {
    final yp = show.yp;
    List<Widget> children = [];
    int line = 0;
    int lineMax = yp?.length ?? 0;
    for (PlanPlayContent yp1 in yp ?? []) {
      PlanPlayContentItem? s;
      PlanPlayContentItem? f;
      int snum = 0;
      bool haveResult = false;
      for (PlanPlayContentItem element in yp1.list ?? []) {
        if (element.r == 1) {
          haveResult = true;
        }
        switch (element.i) {
          case "s":
            s = element;
            break;
          case "f":
            f = element;
            break;
        }
        if (element.s == 1 || element.s == 2) {
          snum += 1;
        }
      }
      if (s == null || f == null) {
        continue;
      }

      String qiuLine = yp1.line ?? '';
      if (qiuLine.startsWith("-")) {
        qiuLine = "主$qiuLine";
      } else if (qiuLine.startsWith(RegExp("[\\d]"))) {
        qiuLine = "主+$qiuLine";
      } else if (qiuLine.startsWith("+")) {
        qiuLine = "主$qiuLine";
      }

      final box = _matchInfoWhiteBox(
          Row(
            children: [
              if (!isViewpoint) ...[
                _matchInfoWhiteBox(QkdText("亚盘")),
                const SizedBox(width: 8.5),
              ],
              _checkContent1(s, snum, haveResult),
              const VerticalDivider(width: 0.5, color: Colours.greyEA),
              _checkContent(qiuLine, ""),
              const VerticalDivider(width: 0.5, color: Colours.greyEA),
              _checkContent1(f, snum, haveResult),
            ],
          ),
          width: double.infinity);
      children.add(box);
      if (line++ < lineMax - 1) {
        children.add(const SizedBox(height: 6));
      }
    }
    return Column(children: children);
  }

  Widget _checkContent1(PlanPlayContentItem? item, int snum, bool haveResult) {
    int? type = item?.s;
    if (snum == 1 && type == 1) {
      type = 0;
    } else if (type == 0) {
      type = null;
    }
    return _checkContent(item?.n ?? "", item?.o ?? "",
        type: type, checked: item?.r == 1, haveResult: haveResult);
  }

  Widget _checkContent(String text, String rate,
      {int? type,
      bool checked = false,
      bool haveResult = false,
      bool expanded = true}) {
    String lt = "荐";
    if (type == 1) {
      lt = "首";
    } else if (type == 2) {
      lt = "次";
    }
    bool half = text.isNotEmpty && rate.isNotEmpty;
    bool bingo = type != null && checked;

    Color? bgColor;
    if (type != null && (matchPlay?.canRead ?? false)) {
      if (matchPlay?.status == 0) {
        bgColor = _notReady;
      } else if (matchPlay?.status == 3) {
        bgColor = Colours.grey99;
      } else if (matchPlay?.status == 4) {
        bgColor = Colours.blue2766D6;
      } else if (bingo) {
        bgColor = Colours.main;
      } else {
        bgColor = Colours.grey99;
      }
    }

    final s = Stack(
      children: [
        Positioned.fill(
            child: Container(
          color: bgColor ?? Colours.greyF7F9FC,
          child: DefaultTextStyle(
            style: TextStyle(
                fontSize: 12,
                color: bgColor != null ? Colors.white : Colours.text),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                if (text.isNotEmpty) QkdText(text),
                if (rate.isNotEmpty && ModeConfig.viewpointOdds) QkdText(rate)
              ],
            ),
          ),
        )),
        if (type != null && ((matchPlay?.canRead ?? false)))
          Positioned(
              left: 0,
              top: 0,
              width: 14,
              height: 14,
              child: Container(
                alignment: Alignment.center,
                decoration: const BoxDecoration(
                    color: Color(0xFFFFB400),
                    borderRadius:
                        BorderRadius.only(bottomRight: Radius.circular(4))),
                child: QkdText(
                  lt,
                  fontSize: 10,
                  color: Colors.white,
                ),
              )),
        if (checked)
          Positioned.fill(
              child: Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              Expanded(child: Container()),
              Expanded(
                  child: Column(
                children: [
                  Expanded(
                      child: Center(
                          child: Container(
                              padding: const EdgeInsets.all(1),
                              decoration: BoxDecoration(
                                  color: bingo ? Colors.white : Colours.main,
                                  shape: BoxShape.circle),
                              child: Icon(
                                Icons.check,
                                size: 8,
                                color: bingo ? Colours.main : Colors.white,
                              )))),
                  if (half) Expanded(child: Container())
                ],
              ))
            ],
          ))
      ],
    );
    return expanded ? Expanded(child: s) : s;
  }

  Widget _matchInfoWhiteBox(Widget child,
      {double? width = 38, double? height = 40, bool show = true}) {
    return DefaultTextStyle(
      style: const TextStyle(fontSize: 12, color: Colours.text),
      child: Container(
        width: width,
        height: height,
        alignment: Alignment.center,
        clipBehavior: Clip.hardEdge,
        decoration: BoxDecoration(
            color: Colours.greyF7F9FC, borderRadius: BorderRadius.circular(4)),
        foregroundDecoration: BoxDecoration(
            border: Border.all(color: const Color(0xffeaeaea)),
            borderRadius: BorderRadius.circular(4)),
        child: child,
      ),
    );
  }
}
